﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Diagnostics;
using DimensionAddIn.V2;

namespace DimensionAddIn
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Debug.WriteLine("addin startup");

            Globals.ThisAddIn.Application.WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(Application_WorkbookOpen);
            Globals.ThisAddIn.Application.WorkbookBeforeSave += new Excel.AppEvents_WorkbookBeforeSaveEventHandler(Application_WorkbookBeforeSave);
            Globals.ThisAddIn.Application.SheetActivate += new Excel.AppEvents_SheetActivateEventHandler(Application_SheetActivate);
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            Debug.WriteLine("addin shutdown");
        }

        #region VSTO generated code

        /// <x:summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// <x:/summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion


        void Application_WorkbookOpen(Excel.Workbook Wb)
        {
            bool isXBook = false;
            Excel.Worksheet coreSheet = null;
            foreach (Excel.Worksheet worksheet in Wb.Sheets)
            {
                if (worksheet.CodeName == "core")
                {
                    Debug.WriteLine("this workbook is x workbook!");
                    coreSheet = worksheet;
                    isXBook = true;
                    break;
                }
            }

            if (isXBook)
            {
                XBook xBook = new XBook();
                xBook.Name = Wb.FullName;

                XTemplate xTemplate = XTemplate.Deserialize(
                    Convert.ToString(coreSheet.XGetCell(1, 1).Value2),
                    Convert.ToString(coreSheet.XGetCell(1, 2).Value2),
                    Convert.ToString(coreSheet.XGetCell(1, 3).Value2));
                xBook.Templates.Add(xTemplate);
                
                XSheet xSheet = new XSheet();
                xSheet.Name = xTemplate.Name;
                xSheet.XTemplate = xTemplate;
                xBook.XSheets.Add(xSheet);

                XBookManager.Add(xBook);
            }
        }

        void Application_SheetActivate(object Sh)
        {
            Excel.Workbook curWorkbook = Globals.ThisAddIn.Application.ActiveWorkbook;
            XBook xBook = XBookManager.Get(curWorkbook.FullName);
            if (xBook != null)
            {
                Excel.Worksheet curSheet = Sh as Excel.Worksheet;
                string codeName = curSheet.CodeName;
                if (!string.IsNullOrEmpty(codeName))
                {
                    foreach (var xSheet in xBook.XSheets)
                    {
                        if (xSheet.Name == codeName)
                        {
                            xSheet.Active(curSheet);
                            return;
                        }
                    }
                }
            }
        }

        void Application_WorkbookBeforeSave(Excel.Workbook Wb, bool SaveAsUI, ref bool Cancel)
        {
            bool hasDxlsAddin = false;
            Windows.BusyIndicatorForm busyForm = new Windows.BusyIndicatorForm();
            busyForm.ShowMask(() =>
            {
                DServ.DExcelServiceClient client = ThisAddIn.CreateClient();
                foreach (var item in Wb.Worksheets)
                {
                    Excel.Worksheet sheet = (Excel.Worksheet)item;
                    if (DocAddIn.Instances.ContainsKey(sheet.Name))
                    {
                        DocAddIn addin = DocAddIn.Instances[sheet.Name];
                        string dumpString = addin.Matrix.ValueTable.Dump();
                        client.SaveValueTable(
                            new Guid("{4DD16CEF-3906-4263-B506-4D90E9CAE34C}"),
                            new Guid("{15787EE0-BD4B-4A21-B79D-90698C24EE5C}"),
                            addin.Schema.DocType,
                            dumpString);
                        hasDxlsAddin = true;
                    }
                }
            });
            if (hasDxlsAddin)
            {
                Cancel = true;
            }
        }

        void Wb_SheetActivate(object Sh)
        {
            Excel.Worksheet sheet = (Excel.Worksheet)Sh;
            Debug.WriteLine(string.Format("sheet activate \"{0}\"", sheet.Name));
        }

        public static DServ.DExcelServiceClient CreateClient()
        {
            System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
            binding.MaxBufferSize = 20 * 1024 * 1024;
            binding.MaxReceivedMessageSize = 20 * 1024 * 1024;
            System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress("http://localhost:20998/DExcelService.svc");
            DServ.DExcelServiceClient client = new DServ.DExcelServiceClient(binding, address);
            return client;
        }
    }
}
